package com.yzw.realm;

import com.yzw.pojo.SysUser;
import com.yzw.service.MenuService;
import com.yzw.service.RoleService;
import com.yzw.service.SysUserService;
import com.yzw.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到用户名和密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
        String username = usernamePasswordToken.getUsername();
//        String password = new String(usernamePasswordToken.getPassword());
        SysUser user = sysUserService.findByUsername(username);
        if(user==null){
            throw new UnknownAccountException("账户不存在");
        }
//        if(!user.getPassword().equals(password)){
//            throw new IncorrectCredentialsException("密码不正确");
//        }
        if(user.getStatus()==0){
            throw new LockedAccountException("账户被冻结");
        }
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,
                user.getPassword(),//这个参数传的是加密后的密码，而不是前台输入的明文密码，否则会报错：java.lang.IllegalArgumentException: Illegal hexadecimal charcter g at index 0
                ByteSource.Util.bytes(user.getSalt()),//salt=username+salt
                this.getName());

        // 存入用户对象
//        SecurityUtils.getSubject().getSession().setAttribute("user", user);
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("user",user);
        session.setTimeout(7*24*3600);
        return info;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser sysUser = (SysUser)principals.getPrimaryPrincipal();
        Long userId = sysUser.getUserId();
        //用户的角色
        List<String> rolsByUserID = roleService.findRolsByUserID(userId);
        //用户的菜单权限
        List<String> permsByUserId = menuService.findPermsByUserId(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(rolsByUserID);
        info.addStringPermissions(permsByUserId);


        return info;
    }

}
